<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ProblemApi } from '@/api/ProblemApi.ts'
import { ReloadOutlined } from '@ant-design/icons-vue'
import type { ProblemVO, SearchParams } from '@/api/Problem.ts'

const router = useRouter()

interface ProblemRecord extends ProblemVO {
  passRate: string
  solveSubmit: string
}

const columns = [
  {
    title: '题目',
    dataIndex: 'title',
    key: 'title',
    align: 'left',
    width: '50%'
  },
  {
    title: '难度',
    dataIndex: 'difficulty',
    key: 'difficulty',
    align: 'center',
    width: '15%'
  },
  {
    title: '通过/提交',
    dataIndex: 'solveSubmit',
    key: 'solveSubmit',
    align: 'center',
    width: '20%'
  },
  {
    title: '通过率',
    dataIndex: 'passRate',
    key: 'passRate',
    align: 'center',
    width: '15%'
  },
]

const loading = ref(false)
const tableData = ref<ProblemRecord[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
})

const baseParams = reactive<SearchParams>({
  title: null,
  difficulty: null,
})

const formatPassRate = (record: Pick<ProblemVO, 'submissionCount' | 'acceptedCount'>) => {
  const submit = Number(record?.submissionCount ?? 0)
  const solved = Number(record?.acceptedCount ?? 0)
  if (!submit || submit <= 0) return '0.00%'
  const rate = (solved / submit) * 100
  return `${rate.toFixed(2)}%`
}

const decorateRecords = (records: ProblemVO[]): ProblemRecord[] => {
  return records.map((item) => ({
    ...item,
    passRate: formatPassRate(item),
    solveSubmit: `${item.acceptedCount}/${item.submissionCount}`,
  }))
}

const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      ...baseParams,
      pageNumber: pagination.current,
      pageSize: pagination.pageSize,
    }
    const data = await ProblemApi.search(params as any)
    const records = data?.records ?? []
    tableData.value = decorateRecords(records)
    pagination.current = Number(data?.pageNumber) || pagination.current
    pagination.pageSize = Number(data?.pageSize) || pagination.pageSize
    pagination.total = Number(data?.totalRow) || records.length
  } finally {
    loading.value = false
  }
}

const handleTableChange = (pag: any) => {
  pagination.current = pag?.current || 1
  pagination.pageSize = pag?.pageSize || 20
  fetchData()
}

const handleRowClick = (record: ProblemRecord) => {
  router.push({
    name: 'problemDetail',
    params: { id: record.id }
  })
}

onMounted(() => {
  fetchData()
})
</script>

<template>
  <div class="flex justify-center px-4 py-6">
    <a-card
      class="w-full max-w-[1080px] rounded-lg shadow-sm"
    >
      <div class="mb-4 flex flex-wrap items-center gap-3">
        <a-input
          v-model:value="baseParams.title"
          allow-clear
          placeholder="按标题搜索"
          class="w-52"
        />
        <a-select
          v-model:value="baseParams.difficulty"
          allow-clear
          placeholder="选择难度"
          class="w-30"
        >
          <a-select-option :value="0">简单</a-select-option>
          <a-select-option :value="1">中等</a-select-option>
          <a-select-option :value="2">困难</a-select-option>
        </a-select>
        <a-button type="primary" @click="() => { pagination.current = 1; fetchData() }">搜索</a-button>
        <a-tooltip title="重置">
          <a-button
            @click="() => { baseParams.title = null; baseParams.difficulty = null; pagination.current = 1; fetchData() }"
            :shape="'default'"
            class="w-9 h-9 p-0 flex items-center justify-center"
          >
            <template #icon>
              <ReloadOutlined />
            </template>
          </a-button>
        </a-tooltip>
      </div>
      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        rowKey="id"
        :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showSizeChanger: false,
        }"
        @change="handleTableChange"
        :customRow="(record: ProblemRecord) => ({
          onClick: () => handleRowClick(record),
          class: 'cursor-pointer hover:bg-blue-50 transition-colors'
        })"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'title'">
            <span class="text-blue-600 hover:text-blue-800 font-medium">{{ record.title }}</span>
          </template>
          <template v-else-if="column.key === 'passRate'">
            <span>{{ record.passRate }}</span>
          </template>
          <template v-else-if="column.key === 'difficulty'">
            <a-tag :color="record.difficulty === 0 ? 'green' : record.difficulty === 1 ? 'orange' : 'red'">
              {{ record.difficulty === 0 ? '简单' : record.difficulty === 1 ? '中等' : '困难' }}
            </a-tag>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>
